package com.kyivmohyla.kma2.server;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.kyivmohyla.kma2.client.LoginService;
import com.kyivmohyla.kma2.client.exception.DelistedException;
import com.kyivmohyla.kma2.client.utils.MD5Hasher;
import com.kyivmohyla.kma2.dao.StaffDao;
import com.kyivmohyla.kma2.factory.DAOFactory;
import com.kyivmohyla.kma2.factory.SpringBeansFactory;
import com.kyivmohyla.kma2.model.Staff;
import com.kyivmohyla.kma2.server.proxy.Proxy;
import com.kyivmohyla.kma2.shared.model.UIStaff;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.CannotGetJdbcConnectionException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

public class LoginServiceImpl extends RemoteServiceServlet implements LoginService {
    @Override
    public UIStaff getByLoginAndPassword(String email, String password) throws DelistedException {
        DAOFactory factory = (DAOFactory) SpringBeansFactory.getInstance().getBeanByName("oracleDaoFactory");
        Staff staff;
        try {
            staff = ((StaffDao) factory.getStaffDao()).getByEmailPassword(email, MD5Hasher.getInstance().getHash(password));
        } catch (EmptyResultDataAccessException e) {
            throw new DelistedException("Invalid login or password");
        } catch (CannotGetJdbcConnectionException e) {
            throw new DelistedException("Could not get connection to database");
        } catch (DataAccessException e) {
            throw new DelistedException(e.getMessage());
        }
        return Proxy.createFromStaff(staff); //TODO Якщо staff прийде null ?
    }

    @Override
    public void login(UIStaff staff) {
        HttpServletRequest request = this.getThreadLocalRequest();
        HttpSession session = request.getSession(true);
        session.setAttribute("currentStaff", staff);
    }

    @Override
    public UIStaff checkLogin() {
        HttpServletRequest request = this.getThreadLocalRequest();
        HttpSession session = request.getSession(false);
        if (session == null || session.getAttribute("currentStaff") == null) {
            return null;
        }
        return (UIStaff) session.getAttribute("currentStaff");
    }

    @Override
    public void logout() {
        HttpServletRequest request = this.getThreadLocalRequest();
        HttpSession session = request.getSession(false);
        if (session == null) {
            return;
        }
        session.invalidate();
    }

}